package com.example.phone.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
//新导入的类


//导入了比较多的类，分不清了，可以全部复制一下


public class LocationOverlayDemo extends Activity {
	
	static MapView mMapView = null;
	
	
	//////////////////////////////新的变量的声明
	MKSearch mSearch = null;
	public static String mStrSuggestions[] = {};
	 ListView mSuggestionList = null;
	//////////////////////////////////////////
	 
	 
	private MapController mMapController = null;

	public MKMapViewListener mMapListener = null;
	FrameLayout mMapViewContainer = null;
	
	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
    public NotifyLister mNotifyer=null;
	
	Button testUpdateButton = null;
	
	EditText indexText = null;
	MyLocationOverlay myLocationOverlay = null;
	int index =0;
	LocationData locData = null;
	GraphicsOverlay graphicsOverlay = null;
	////////////////////////////////////
	
	
	Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(LocationOverlayDemo.this, "msg:" +msg.what, Toast.LENGTH_SHORT).show();
        };
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DemoApplication app = (DemoApplication)this.getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(DemoApplication.strKey,new DemoApplication.MyGeneralListener());
        }
        setContentView(R.layout.activity_locationoverlay);
        mMapView = (MapView)findViewById(R.id.bmapView);
        mMapController = mMapView.getController();
        
        initMapView();
        
        mLocClient = new LocationClient( this );
        mLocClient.registerLocationListener( myListener );
        
        ////////////////////////////////////////////
        graphicsOverlay = new GraphicsOverlay(mMapView);
        mMapView.getOverlays().add(graphicsOverlay);
        
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll");     //设置坐标类型
        option.setScanSpan(5000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        mMapView.getController().setZoom(14);
        mMapView.getController().enableClick(true);
        
        mMapView.setBuiltInZoomControls(true);
        mMapListener = new MKMapViewListener() {
			
			@Override
			public void onMapMoveFinish() {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null){
					title = mapPoiInfo.strText;
					Toast.makeText(LocationOverlayDemo.this,title,Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub
				
			}
		};
		///////////////////////////////////////////新加的
		mMapView.regMapViewListener(DemoApplication.getInstance().mBMapManager, mMapListener);
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
	    myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		mMapView.refresh();
		
		
		 mSearch = new MKSearch();
	        mSearch.init(app.mBMapManager, new MKSearchListener(){

	            @Override
	            public void onGetPoiDetailSearchResult(int type, int error) {
	                if (error != 0) {
	                    Toast.makeText(LocationOverlayDemo.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
	                }
	                else {
	                    Toast.makeText(LocationOverlayDemo.this, "成功，查看详情页面", Toast.LENGTH_SHORT).show();
	                }
	            }
	            
	            public void onGetPoiResult(MKPoiResult res, int type, int error) {
	                // 错误号可参考MKEvent中的定义
	                if (error != 0 || res == null) {
	                    Toast.makeText(LocationOverlayDemo.this, "抱歉，未找到结果", Toast.LENGTH_LONG).show();
	                    return;
	                }
	                // 将地图移动到第一个POI中心点
	                if (res.getCurrentNumPois() > 0) {
	                    // 将poi结果显示到地图上
	                    MyPoiOverlay poiOverlay = new MyPoiOverlay(LocationOverlayDemo.this, mMapView, mSearch);
	                    poiOverlay.setData(res.getAllPoi());
	                  //  mMapView.getOverlays().clear();
	                    mMapView.getOverlays().add(poiOverlay);
	                    mMapView.refresh();
	                    //当ePoiType为2（公交线路）或4（地铁线路）时， poi坐标为空
	                    for( MKPoiInfo info : res.getAllPoi() ){
	                    	if ( info.pt != null ){
	                    		mMapView.getController().animateTo(info.pt);
	                    		break;
	                    	}
	                    }
	                } else if (res.getCityListNum() > 0) {
	                    String strInfo = "在";
	                    for (int i = 0; i < res.getCityListNum(); i++) {
	                        strInfo += res.getCityListInfo(i).city;
	                        strInfo += ",";
	                    }
	                    strInfo += "找到结果";
	                    Toast.makeText(LocationOverlayDemo.this, strInfo, Toast.LENGTH_LONG).show();
	                }
	            }
	            public void onGetDrivingRouteResult(MKDrivingRouteResult res,
	                    int error) {
	            }
	            public void onGetTransitRouteResult(MKTransitRouteResult res,
	                    int error) {
	            }
	            public void onGetWalkingRouteResult(MKWalkingRouteResult res,
	                    int error) {
	            }
	            public void onGetAddrResult(MKAddrInfo res, int error) {
	            }
	            public void onGetBusDetailResult(MKBusLineResult result, int iError) {
	            }
	            @Override
	            public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
	                if (arg1 != 0 || res == null) {
	                    Toast.makeText(LocationOverlayDemo.this, "抱歉，未找到结果", Toast.LENGTH_LONG).show();
	                    return;
	                }
	                int nSize = res.getSuggestionNum();
	                mStrSuggestions = new String[nSize];

	                for (int i = 0; i < nSize; i++) {
	                    mStrSuggestions[i] = res.getSuggestion(i).city + res.getSuggestion(i).key;
	                }
	                ArrayAdapter<String> suggestionString = new ArrayAdapter<String>(LocationOverlayDemo.this, android.R.layout.simple_list_item_1,mStrSuggestions);
	                mSuggestionList.setAdapter(suggestionString);
	                Toast.makeText(LocationOverlayDemo.this, "suggestion callback", Toast.LENGTH_LONG).show();

	            }
	            
	        });
	    //    mSuggestionList = (ListView) findViewById(R.id.listView1);
		testUpdateButton = (Button)findViewById(R.id.button1);
		OnClickListener clickListener = new OnClickListener(){
				public void onClick(View v) {
					 mSearch.poiSearchNearBy("大学", new GeoPoint((int) (43.831 * 1E6), (int) (125.432 * 1E6)), 5000);
				}
	        };
	    testUpdateButton.setOnClickListener(clickListener);
	    
	   
    }
   ////////////////////////////////////////////////////////////////end 
    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }
    
    
    @Override
    protected void onDestroy() {
        if (mLocClient != null)
            mLocClient.stop();
        mMapView.destroy();
        DemoApplication app = (DemoApplication)this.getApplication();
        if (app.mBMapManager != null) {
            app.mBMapManager.destroy();
            app.mBMapManager = null;
        }
        super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    	
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	mMapView.onRestoreInstanceState(savedInstanceState);
    }
    
    public void testUpdateClick(){
        mLocClient.requestLocation();
    }
    private void initMapView() {
        mMapView.setLongClickable(true);
        //mMapController.setMapClickEnable(true);
        //mMapView.setSatellite(false);
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

	
	/**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return ;
            
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            myLocationOverlay.setData(locData);
            mMapView.refresh();
           
            mMapController.animateTo(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)), mHandler.obtainMessage(1));
            
            //////显示大学
            mSearch.poiSearchNearBy("大学", new GeoPoint((int) (locData.latitude * 1E6), (int) (locData.longitude * 1E6)), 5000);
           //////////////////////////////////////////////////start 
            int lat = (int) (locData.latitude*1E6);
    	   	int lon = (int) (locData.longitude*1E6);   	
    	   	GeoPoint pt1 = new GeoPoint(lat, lon);
    	   	
    	    /////////////////////////////////////////////////end
    	   	
    	  //构建点并显示///////////////////////////////////////start
    	   	
      		Geometry circleGeometry = new Geometry();
      	
      		circleGeometry.setCircle(pt1, 2000);
      		
      		Symbol circleSymbol = new Symbol();
     		Symbol.Color circleColor = circleSymbol.new Color();
     		circleColor.red = 0;
     		circleColor.green = 255;
     		circleColor.blue = 0;
     		circleColor.alpha = 126;
      		circleSymbol.setSurface(circleColor,0,6);
      		
      		Graphic circleGraphic = new Graphic(circleGeometry, circleSymbol);
      		
      		graphicsOverlay.setData(circleGraphic);
      		//mMapView.refresh();
      		//////////////////////////////////////////////////////////end

        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }
    
    public class NotifyLister extends BDNotifyListener{
        public void onNotify(BDLocation mlocation, float distance) {
        }
    }

}


